package admin.controllers;

import helpers.GoogleStorageHelper;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import admin.models.ApplicationTemplateModel;
import entities.ApplicationTemplate;

@SuppressWarnings("serial")
public class ApplicationTemplateDownloadServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		String path = ((HttpServletRequest) request).getRequestURI();
		String id = URLDecoder.decode(path.replaceAll(request.getServletPath() + "/", ""),"UTF-8");
		
		if (id == null || id.isEmpty()) {
			response.sendRedirect("/admin/apptemplate/list");
			return ;
		}
		
		try {
			returnFile(response, id);
		} catch (Exception e) {
			response.sendRedirect("/admin/apptemplate/list");
			return;
		}
		
		
	}
	
	private void returnFile(HttpServletResponse response, String templateId) {
		ApplicationTemplateModel appTemplateModel = ApplicationTemplateModel.getInstance();
		ApplicationTemplate template = appTemplateModel.get(templateId);
		
		try {
			String parentFolder = "";
			String[] splitFileName = GoogleStorageHelper.getListFile(templateId);
			
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			ZipOutputStream zos = new ZipOutputStream(baos);
			/*
			 * read all files and compress
			 */
			for (String filename : splitFileName) {
				String prefix = "/gs/" + GoogleStorageHelper.BUCKETNAME + "/" + templateId+ "/";
				String fileNoPrefix = filename.replace(prefix, "");
		
				if (parentFolder.length() == 0) {
					parentFolder = fileNoPrefix.split("/")[0];
				}
				fileNoPrefix = fileNoPrefix.replace(parentFolder + "/", "");
				zos.putNextEntry(new ZipEntry(fileNoPrefix.trim()));
				
				if (template != null && filename.contains("home.php")) {
					zos.write(template.getHome().getBytes());
				} else if (template != null && filename.contains("header.php")) {
					zos.write(template.getHeader().getBytes());
				} else if (template != null && filename.contains("footer.php")) {
					zos.write(template.getFooter().getBytes());
				} else if (template != null && filename.contains("layouts.php")) {
					zos.write(template.getLayout().getBytes());
				} else if (template != null && filename.contains("contact.php")) {
					zos.write(template.getContact().getBytes());
				} else if (template != null && filename.contains("static.php")) {
					zos.write(template.getStaticPage().getBytes());
				} else if (template != null && filename.contains("gsearch.php")) {
					zos.write(template.getSearch().getBytes());
				} else if (template != null && filename.contains("library.php")) {
					zos.write(template.getLibrary().getBytes());
				} else {
					GoogleStorageHelper.readFileGoogleStorage(filename, zos);
				}
			}
			zos.closeEntry();
			zos.flush();
			baos.flush();
			zos.close();
			baos.close();
			/*
			 * return client zip file
			 */
			byte[] zip = baos.toByteArray();
			ServletOutputStream sos = response.getOutputStream();
			response.setContentType("application/zip");
			response.setHeader("Content-Disposition", "attachment; filename=\""
					+ templateId + ".zip\"");
			sos.write(zip);
			sos.flush();
		} catch (Exception e) {
			e.printStackTrace(System.err);
			System.out.println(
							"Error when trying to download template. Please try again later !");
		}
		
	}
}
